'use strict'

//require('./lib/logger')
//require('./lib/server')
//require('./lib/requestControl')
let base32 = require('base32')
let userServerConfig = require('./config').userServerConfig
let http = require('http')
let url = require('url')
let fs = require('fs')
let userDao = require('./dao/userDao')

http.createServer(function(request, response) {
  response.setHeader("Access-Control-Allow-Origin", "*")
  if (request.method !== 'GET') {
    response.end()
    return
  }
  var pathname = url.parse(request.url).pathname

  var querystring = url.parse(request.url, true).query
    console.log(pathname)
      console.log(querystring)
  if (pathname === '/createUser') {
    let username = querystring.username
    let password = querystring.password

    if (!/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(username) || !/^([a-z]|[A-Z]|[0-9]){3,99}$/.test(password)) {
      sendData(1, response)
      return
    }
    password = base32.decode(password)
    //判断名字是否已经存在
    userDao.getUserByUsername(username, function(err, res) {
      if (err || res) { //名字已经存在
        sendData(2, response)
        return
      }
      userDao.newAndSave(username, password, function(err) {
        if (err) {
          sendData(3, response)
          return
        }
        sendData(0, response)
      })
    })

  } else if (pathname === '/userLogin') {
    let username = querystring.username
    let password = querystring.password

    if (!/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(username) || !/^([a-z]|[A-Z]|[0-9]){3,99}$/.test(password)) {
      sendData(1, response)
      return
    }
    password = base32.decode(password)
    //判断是否已经存在
    userDao.getUserByQuery({
      username: username,
      password: password
    }, function(err, res) {
      if (err || !res) {
        sendData(2, response)
        return
      }
      sendData({
        error: 0
      }, response)
    })

  } else if (pathname === '/verifyUser') {
    let username = querystring.name
    let password = querystring.pwd

    if (!/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(username) || !/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(password)) {
      sendData(1, response)
      return
    }
    password = base32.decode(password)
    //判断是否已经存在
    userDao.getUserByQuery({
      username: username,
      password: password
    }, function(err, res) {
      if (err || !res) {
        sendData(2, response)
        return
      }
      sendData({
        error: 0,
        userId: res._id
      }, response)
    })

  } else {
    response.end()
    return
  }

}).listen(userServerConfig.port)
console.log(`用户服务器启动 ${userServerConfig.ip}:${userServerConfig.port}`)


function sendData(data, response) {
  if (typeof data === 'number') {
    data = {
      error: data
    }
  }
  data = JSON.stringify(data)
  response.end(data)
}
